/**
 *
 */

import axios from 'axios'
import { setCookie, timestamp } from '@/utils/utils'
import router from '@/router'
import store from '@/store'
import Cookies from 'js-cookie'

const TokenKey = 'Session_Token'

export function getToken() {
  return Cookies.get(TokenKey)
}

// 环境的切换
// if (process.env.NODE_ENV === 'development') {
//   axios.defaults.baseURL = api.BASEURL
// } else if (process.env.NODE_ENV === 'production') {
//   axios.defaults.baseURL = api.EGHURL
// }

// post 请求头设置
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
axios.defaults.headers.post['Content-Type'] = 'application/json'
// axios.defaults.withCredentials = true
// 创建axios实例

const service = axios.create({
  // eslint-disable-next-line no-undef
  baseURL: process.env.NODE_ENV === 'development' ? api.PROXYURL : api.PRDURL,
  timeout: 60000 // 请求超时时间
})
let serviceArr = []
// request拦截器
service.interceptors.request.use(
  config => {
    //
    if (config.url.includes('/FTKJWLHYPT/frtOrder/downloadDynamicNode') || config.url.indexOf('export') > -1 || config.url.indexOf('Export') > -1) {
      //
      config.responseType = 'blob' // 服务请求类型
    }
    if (serviceArr.length === 0) {
      window.parent._$store.dispatch('app/loading_status', true)
    }
    serviceArr.push('service')

    // let token = sessionStorage.getItem('Session_Token')
    // let token = localStorage.getItem('Session_Token')
    let token = store.state.user.Session_Token
    if (token) {
      // 判断是否存在token，如果存在的话，则每个http header都加上token
      config.headers.Token = token //请求头加上token
    }
    if (store.state.app.mdlUrl) {
      config.headers.pageUrl = store.state.app.mdlUrl.replace('/layout', '')
    }
    return config
  },
  err => {
    if (serviceArr.length === 1) {
      window.parent._$store.dispatch('app/loading_status', false)
    }
    serviceArr.pop()
    return Promise.reject(err)
  }
)

/**
 * http response 拦截器 两个对应不同的baseURL
 */
service.interceptors.response.use(
  response => {
    if (response.config.responseType == 'arraybuffer') {
      return response
    }
    if (serviceArr.length === 1) {
      window.parent._$store.dispatch('app/loading_status', false)
    }
    serviceArr.pop()
    const code = response.status
    if (response.data.success === '2') {
      window._$message({
        message: response.data.message || response.data.msg,
        type: 'error',
        showClose: true
      })
      window.parent._$store.dispatch('app/process_login_status', true)
    } else if (response.data.success === '1') {
      return response
    } else if (response.data.success == '10086') {
      return response
    } else if (response.data.errorCode == '10') {
      window._$message({
        message: response.data.message || response.data.msg,
        type: 'error',
        showClose: true
      })
      setCookie('FLT_UUID_DX_H', '')
      setCookie('DPTID_DX_H', '')
      setCookie('USERNAME_DX_H', '')
      setCookie('USR_CODE_DX_H', '')
      setCookie('USR_RLES_DX_H', '')
      setCookie('UserId_DX_H', '')
      setCookie('SESSION', '')
      setCookie('Session_Token', '')
      setCookie('FLT_NAME_DX_H', '')
      router.replace({
        path: '/login'
      })
    } else if (response.data.errorCode == '20009') {
      window._$message({
        message: response.data.message || response.data.msg,
        type: 'error',
        showClose: true
      })
      setCookie('FLT_UUID_DX_H', '')
      setCookie('DPTID_DX_H', '')
      setCookie('USERNAME_DX_H', '')
      setCookie('USR_CODE_DX_H', '')
      setCookie('USR_RLES_DX_H', '')
      setCookie('UserId_DX_H', '')
      setCookie('SESSION', '')
      setCookie('Session_Token', '')
      setCookie('FLT_NAME_DX_H', '')
      router.replace({
        path: '/login'
      })
      return
    } else if (response.data.success == '20009') {
      window._$message({
        message: response.data.message || response.data.msg,
        type: 'error',
        showClose: true
      })
      setCookie('FLT_UUID_DX_H', '')
      setCookie('DPTID_DX_H', '')
      setCookie('USERNAME_DX_H', '')
      setCookie('USR_CODE_DX_H', '')
      setCookie('USR_RLES_DX_H', '')
      setCookie('UserId_DX_H', '')
      setCookie('SESSION', '')
      setCookie('Session_Token', '')
      setCookie('FLT_NAME_DX_H', '')
      router.replace({
        path: '/login'
      })
      return
    } else if (code == 200) {
      if (response.data.success == 0) {
        window._$message({
          message: response.data.message || response.data.msg,
          type: 'error',
          showClose: true
        })
      } else {
        return response
      }
    } else {
      window._$message({
        message: response.data.message || response.data.msg,
        type: 'error',
        showClose: true
      })
    }
  },
  error => {
    if (serviceArr.length === 1) {
      window.parent._$store.dispatch('app/loading_status', false)
    }
    serviceArr.pop()
    window._$message({
      message: '系统错误，请联系管理员!',
      type: 'error',
      showClose: true
    })
    return Promise.reject(error)
  }
)

export function get(url, params) {
  return new Promise((resolve, reject) => {
    service
      .get(timestamp(url), {
        params: params
      })
      .then(res => {
        res && resolve(res.data)
      })
      .catch(err => {
        reject(err)
      })
  })
}

/**
 * post方法，对应post请求,两个post对应不同的baseURL
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function post(url, params) {
  return new Promise((resolve, reject) => {
    service
      .post(url, JSON.stringify(params))
      .then(res => {
        resolve(res.data)
      })
      .catch(err => {
        reject(err)
      })
  })
}

/**
 * post方法，对应post请求,两个post对应不同的baseURL
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function postFormData(url, formData) {
  return new Promise((resolve, reject) => {
    service
      .post(timestamp(url), formData)
      .then(res => {
        resolve(res.data)
      })
      .catch(err => {
        reject(err)
      })
  })
}

export function fileGet(url, params) {
  // const service = axios.create({
  //   baseURL: process.env.NODE_ENV === 'development' ? '' : window.api.baseURL,
  //   timeout: 10000 // 请求超时时间
  // })
  return new Promise((resolve, reject) => {
    service
      .get(timestamp(url), {
        params: params,
        responseType: 'arraybuffer'
      })
      .then(res => {
        res && resolve(res)
      })
      .catch(err => {
        reject(err)
      })
  })
}

export function filePost(url, params) {
  return new Promise((resolve, reject) => {
    service
      .post(url, params, {
        responseType: 'arraybuffer'
      })
      .then(res => {
        res && resolve(res)
      })
      .catch(err => {
        reject(err)
      })
  })
}
